package com.ruoyi.web.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.web.core.config.WeChatURL;
import com.ruoyi.web.entity.WxResult;
import com.ruoyi.web.entity.dao.WechatLoginRequest;
import com.ruoyi.web.entity.po.WeChatUser;
import com.ruoyi.web.mapper.WechatMapper;
import com.ruoyi.web.service.IWechatService;
import com.ruoyi.web.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class WechatServiceImpl extends ServiceImpl<WechatMapper, WeChatUser> implements IWechatService {


    @Override
    public ResponseResult getUserInfoMap(WechatLoginRequest loginRequest) {
        Map<String, Object> map = new HashMap<>(5);
        map.put("js_code",loginRequest.getCode());
        map.put("appid", "wxe29f58902775ce8d");
        map.put("secret","5951f721d928c5e31afce3273226134f");
        WxResult wxResult = getWeChatOpenid(map);
        if(wxResult != null && "0".equals(wxResult.getErrcode())) {
           return ResponseResult.success(wxResult);
        }else {
            log.error("【error】 ：openid 授权失败 -- 返回数据内容" + JSONObject.toJSONString(wxResult));
            return ResponseResult.error("授权失败，请稍后再试");
        }

    }
    /**
     * 获取微信用户openId
     * 微信端请求成功默认返回 成功码 0
     * @param map 请求参数
     * @return
     */
    public WxResult getWeChatOpenid(Map<String, Object> map){
        try {

            return JSON.parseObject(HttpUtil.get(WeChatURL.WX_SESSION,  map), WxResult.class);
        } catch (Exception e) {
            log.error("【error】---> 获取微信openid，解码密钥失败：" + e.getMessage(),e);
        }
        return null;
    }
}
